package com.pace.ribbon.exception;

import com.pace.ribbon.dto.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice// 统一异常处理
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R defaultErrorHandler(HttpServletRequest rq, Exception e) throws Exception {
        logger.error("服务器后台程序出现异常", e);
        R r = new R();

        if (e instanceof NoHandlerFoundException) {
            r.setCode(404);
        } else {
            r.setCode(500);
        }
        r.setData(e.getMessage());
        logger.error(r.toString());
        System.out.println(r);
        return r;
    }
}
